package com.absorbx.security;

import java.util.Collection;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.userdetails.UsernameNotFoundException;

import com.absorbx.jcr.dao.ContentDao;

public class UserServiceJcrImpl implements UserService {

	final Logger logger = LoggerFactory.getLogger(UserServiceJcrImpl.class);
	private String userPath;
	private String rolePath;
	private String defaultRole;
	private ContentDao contentDao;

	public User loadUserByUsername(String username)
			throws UsernameNotFoundException {
		User user = null;
		Object obj = contentDao.findByPath(userPath + "/" + username);
		if (obj != null) {
			user = (User) obj;
		}
		return user;
	}

	@Override
	public User addUser(User user) {
		user.setPath(userPath+"/"+user.getUsername());
		Role userRole = this.getRoleByName(defaultRole);
		user.addRole(userRole);

		return (User) contentDao.save(user);
	}

	@Override
	public Role addRole(Role role) {
		role.setPath(rolePath+"/"+role.getName());
		return (Role) contentDao.save(role);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<Role> getRoles() {
		return contentDao.getAll(Role.class);
	}

	public void setContentDao(ContentDao contentDao) {
		this.contentDao = contentDao;
	}

	@Override
	public Role getRoleByName(String name) {

		return (Role) contentDao.findByPath(rolePath + "/" + name);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> getUsers() {
		String path = userPath + "//";
		return (List<User>) contentDao.getAllInScope(path, User.class);
	}

	public void setUserPath(String userPath) {
		this.userPath = userPath;
	}

	public void setRolePath(String rolePath) {
		this.rolePath = rolePath;
	}

	public void setDefaultRole(String defaultRole) {
		this.defaultRole = defaultRole;
	}

	@Override
	public void updateUser(User user) {
		contentDao.update(user);
		
	}

}
